const http = require('http');
const https = require('https');
const { URL } = require('url');

class HTTPProxyServer {
    constructor(port = 8080) {
        this.port = port;
        this.server = http.createServer();
        this.setupHandlers();
    }

    setupHandlers() {
        // 处理 HTTP CONNECT 方法 (用于 HTTPS)
        this.server.on('connect', this.handleConnect.bind(this));
        
        // 处理普通 HTTP 请求
        this.server.on('request', this.handleRequest.bind(this));
    }

    // 代理 HTTPS 连接 (CONNECT 方法)
    handleConnect(req, clientSocket, head) {
        console.log(`代理 CONNECT: ${req.url}`);
        
        const [hostname, port] = req.url.split(':');
        const serverPort = parseInt(port) || 443;

        const net = require('net');
        const serverSocket = new net.Socket();

        serverSocket.connect(serverPort, hostname, () => {
            // 告诉客户端连接已建立
            clientSocket.write('HTTP/1.1 200 Connection Established\r\n\r\n');
            
            // 建立双向数据流
            serverSocket.pipe(clientSocket);
            clientSocket.pipe(serverSocket);
        });

        serverSocket.on('error', (err) => {
            clientSocket.write('HTTP/1.1 500 Connection Error\r\n\r\n');
            clientSocket.end();
        });
    }

    // 代理 HTTP 请求
    handleRequest(req, res) {
        // 客户端发送完整 URL: GET http://example.com/path
        console.log(`代理请求: ${req.method} ${req.url}`);
        
        const url = new URL(req.url);
        
        const options = {
            hostname: url.hostname,
            port: url.port || (url.protocol === 'https:' ? 443 : 80),
            path: url.pathname + url.search,
            method: req.method,
            headers: req.headers
        };

        const httpModule = url.protocol === 'https:' ? https : http;

        const proxyReq = httpModule.request(options, (proxyRes) => {
            // 转发响应头和状态码
            res.writeHead(proxyRes.statusCode, proxyRes.headers);
            proxyRes.pipe(res);
        });

        proxyReq.on('error', (err) => {
            res.writeHead(500);
            res.end(`代理错误: ${err.message}`);
        });

        // 转发请求体
        req.pipe(proxyReq);
    }

    start() {
        this.server.listen(this.port, () => {
            console.log(`🔄 HTTP代理服务器启动在端口 ${this.port}`);
            console.log(`📋 客户端配置: HTTP代理 127.0.0.1:${this.port}`);
        });
    }
}
